package com.ethink.framework.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ethink.framework.common.util.RsaUtils;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * jwt工具类
 *
 * @author yunduo
 */
public class JwtUtils {
    /**
     * rsa公钥
     */
    public static final String RSA_PUBLIC_KEY = "jwt_pub_key.txt";
    /**
     * rsa私钥
     */
    public static final String RSA_PRIVATE_KEY = "jwt_pri_key.txt";


    public static final RSAPublicKey PUBLIC_KEY;
    public static final RSAPrivateKey PRIVATE_KEY;
    public static final Algorithm ALGORITHM_RSA256;

    static {
        PUBLIC_KEY = RsaUtils.getPublicKeyObj(RSA_PUBLIC_KEY);
        PRIVATE_KEY = RsaUtils.getPrivateKeyObj(RSA_PRIVATE_KEY);
        ALGORITHM_RSA256 = Algorithm.RSA256(PUBLIC_KEY, PRIVATE_KEY);
    }

    /**
     * 生成jwt token
     *
     * @param payload
     * @return
     */
    public static String create(JwtPayload payload) {
        return JWT.create()
                .withIssuer(payload.getIss())
                .withExpiresAt(payload.getExp())
                .withSubject(payload.getSub())
                .withAudience(payload.getAud())
                .withNotBefore(payload.getNbf())
                .withIssuedAt(payload.getIat())
                .withJWTId(payload.getJti())
                .sign(ALGORITHM_RSA256);
    }


    /**
     * 验证 jwt token
     *
     * @param token
     * @param sub
     * @return
     */
    public static DecodedJWT verify(String token, String sub) {
        JWTVerifier verifier = JWT.require(ALGORITHM_RSA256)
                .withSubject(sub)
                .build(); //Reusable verifier instance
        return verifier.verify(token);
    }

    /**
     * decode
     *
     * @param token
     * @return
     */
    public static DecodedJWT decode(String token) {
        return JWT.decode(token);
    }
}
